package com.example.datadictionary.controller;

import com.example.datadictionary.service.DatabaseService;
import com.example.datadictionary.service.ExcelService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
public class DataDictionaryController {

    @Autowired
    private DatabaseService databaseService;

    @Autowired
    private ExcelService excelService;

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("tables", databaseService.getTableInfo());
        return "index";
    }

    @PostMapping("/generate")
    public void generate(
            @RequestParam(defaultValue = "data_dictionary") String fileName,
            HttpServletResponse response
    ) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        String encodedFileName = URLEncoder.encode(fileName + ".xlsx", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

        // 生成Excel并写入响应流
        try (Workbook workbook = excelService.generateExcel()) {
            workbook.write(response.getOutputStream());
        }
    }
}